import {useMemberStore} from '../stores/modules/member.js'
import { toast,modal } from '../utils/extendApi.js'
import Request from './request.js'
import { env } from './env.js'
const memberStore = useMemberStore()
// 实例化Request的成员
const requestInstance = new Request({
	baseUrl:env.baseUrl,
	timeout:15000, 
	isLoading:false,
})
// 手动配置请求拦截器 
requestInstance.interceptor.request = (config)=>{  
	if(memberStore.profile.token){
		config.header['token']=memberStore.profile.token
	}else{
		// 如果本地没有token，那么就跳转到登录页面
		// uni.navigateTo({
		// 	url:'/pages/login/login'
		// })
	}
	return config
}
requestInstance.interceptor.response = async(response)=>{
	const {isSuccess,data} = response
	// 如果返回的false说明网络异常，进行提示
	if(!isSuccess){
		uni.showToast({
			title:'网络异常请重试',
			icon:"error"
		})
		return response
	}	
	// 判断服务器返回的状态码
	switch(data.code){
		case 200:
			return data
		case 208:
			 const res = await modal({
				content:'鉴权失败，请重新登录',
				showCancel:false //不显示取消按钮
			})
			if(res){
				// 清除token和本地的全部信息
				memberStore.clearProfile()
				uni.navigateTo({
					url:'/pages/login/login'
				})
			}
			return Promise.reject(response)
		default:
			toast({
				title:'程序出现异常，请联系客服或稍后重试'
			})
			return Promise.reject(response)
			break		
	}
}  

export default requestInstance


